<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/8/22
 * Time: 17:28
 */

namespace Goods\Controller;


use Common\Controller\AdminbaseController;
use Common\Model\AttrDetailModel;
use Common\Model\AttributeModel;
use Common\Model\CartModel;
use Common\Model\CategoryModel;
use Common\Model\ProAttrModel;
use Common\Model\ProductModel;
use Common\Model\ProOptionModel;

class IndexController extends AdminbaseController
{
    private $product_model;
    private $pro_attr_model;
    private $pro_option_model;
    private $attr_detail_model;
    private $attribute_model;
    private $category_model;
    private $cart_model;

    public function __construct()
    {
        parent::__construct();
        $this->product_model        = new ProductModel();
        $this->pro_option_model     = new ProOptionModel();
        $this->pro_attr_model       = new ProAttrModel();
        $this->attr_detail_model    = new AttrDetailModel();
        $this->attribute_model      = new AttributeModel();
        $this->category_model       = new CategoryModel();
        $this->cart_model           = new CartModel();
    }

    public function index() {
        $this->__list();
        $this->display();
    }

    public function __list() {
        $fields = [
            'product_name'  => ["field" => "a.product_name", "operator" => "like", 'datatype' => 'string'],
            'status'        => ["field" => "a.status", "operator" => "=", 'datatype' => 'string'],
            'pro_id'        => ["field" => "a.pro_id", "operator" => "=", 'datatype' => 'string'],
        ];

        $where_ands = [];
        if (IS_POST) {
            foreach ($fields as $param => $val) {
                if (isset($_POST[$param]) && !empty($_POST[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $datatype = $val['datatype'];
                    $get = $_POST[$param];
                    $_GET[$param] = $get;

                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    if ($datatype == 'time')
                        $get = strtotime($get);
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        } else {
            foreach ($fields as $param => $val) {
                if (isset($_GET[$param]) && !empty($_GET[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $datatype = $val['datatype'];
                    $get = $_GET[$param];
                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    if ($datatype == 'time')
                        $get = strtotime($get);
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        }
        $where = join(" and ", $where_ands);
        $where .= $where ? ' and a.if_show= "'.ProductModel::SHOW_YES.'"' : 'a.if_show="'.ProductModel::SHOW_YES.'"';

        $count = $this->product_model
            ->alias('a')
            ->join('left join he_category as b on a.cate_id = b.cate_id')
            ->where($where)
            ->count();

        $page = $this->page($count, C("PAGE_NUMBER"));


        $result = $this->product_model
            ->alias('a')
            ->join('left join he_category as b on a.cate_id = b.cate_id')
            ->where($where)
            ->field('a.*, b.cate_name')
            ->limit($page->firstRow, $page->listRows)
            ->order('pro_id desc')
            ->select();
//        dump($this->product_model->getLastSql());

        $this->assign('formget', I(''));
        $this->assign('list', $result);
        $this->assign("Page", $page->show());
    }

    /**
     * 添加
     */
    public function add()
    {
        if(IS_POST) {
//            dump($_POST['post']);exit;
            if (!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])) {
                foreach ($_POST['photos_url'] as $key => $url) {
                    $photourl = sp_asset_relative_url($url);
                    $_POST['post']['smeta'][] = ["url" => $photourl, "alt" => $_POST['photos_alt'][$key]];
                }
            }


            $post = I('post.post');//var_dump(I('post.illness'));exit;
            if(!$post['cate_id']) {
                $this->error('请选择类型');
            }
            $attr = $post['attr'];
            if(!$attr) {
                $this->error('请至少关联一个属性');
            }
            if(!$post['cover_photo']) {
                $this->error('请添加封面');
            }
            $data['smeta']          = json_encode($post['smeta']);
            $data['content']        = htmlspecialchars_decode($post['content']);
            $data['option_content'] = htmlspecialchars_decode($post['option_content']);

            $data['describe']       = $post['describe'];
            $data['cate_id']        = $post['cate_id'];
            $data['tag_id']         = $post['tag_id'];
            $data['product_name']   = $post['product_name'];
            $data['cover_photo']    = $post['cover_photo'];
            $data['virtual_num']    = $post['virtual_num'];
            $data['price']          = $post['price'];
            $data['sale_price']     = $post['sale_price'];
            $data['freight']        = $post['freight'];
            $data['create_time']    = getTime();
            $data['attr']           = implode(',', $attr);

//            dump($data);//exit;

            $this->product_model->startTrans();
            $iscommit = true;

            $product_id = $this->product_model->add($data);
            if($product_id == false) {
                $iscommit = false;
            }
            foreach($attr as $k => $v) {
                $info[] = array(
                    'pro_id'        => $product_id,
                    'attr_id'       => $v,
                );
            }
//            dump($info);exit;
            if($this->pro_attr_model->addAll($info) == false) {
                $iscommit = false;
            }
            if($iscommit) {
                $this->product_model->commit();
                $this->success('', U('index'));
            } else {
                $this->product_model->rollback();
                $this->error();
            }


        } else {
            $this->assign('attribute', $this->attribute_model->getAttrCheck());
            $this->assign('category', $this->category_model->getCateOption());
            $this->display();
        }
    }

    public function edit() {
        if(IS_POST) {
//            dump($_POST);die;
            if (!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])) {
                foreach ($_POST['photos_url'] as $key => $url) {
                    $photourl = sp_asset_relative_url($url);
                    $_POST['post']['smeta'][] = ["url" => $photourl, "alt" => $_POST['photos_alt'][$key]];
                }
            }


            $post = I('post.post');
            if(!$post['cate_id']) {
                $this->error('请选择类型');
            }
            $attr = $post['attr'];
            if(!$attr) {
                $this->error('请至少关联一个属性');
            }
            if(!$post['cover_photo']) {
                $this->error('请添加封面');
            }
            $data['smeta']          = json_encode($post['smeta']);
            $data['content']        = htmlspecialchars_decode($post['content']);
            $data['option_content']        = htmlspecialchars_decode($post['option_content']);

            $data['describe']       = $post['describe'];
            $data['pro_id']         = $post['pro_id'];
            $data['cate_id']        = $post['cate_id'];
            $data['tag_id']         = $post['tag_id'];
            $data['product_name']   = $post['product_name'];
            $data['cover_photo']    = $post['cover_photo'];
            $data['virtual_num']    = $post['virtual_num'];
            $data['price']          = $post['price'];
            $data['sale_price']     = $post['sale_price'];
            $data['freight']        = $post['freight'];
            $data['total_number']   = $post['total_number'];
            $data['create_time']    = getTime();
            $data['attr']           = implode(',', $attr);

//            dump($data);exit;

            $this->product_model->startTrans();
            $iscommit = true;

            $product_id = $this->product_model->save($data);
            if($product_id == false) {
                $iscommit = false;
            }
            if($attr != $this->product_model->where(['pro_id' => $post['pro_id']])->getField('attr')) {
                $this->pro_attr_model->where(['pro_id' => $post['pro_id']])->delete();
                $this->pro_option_model->where(['pro_id' => $post['pro_id']])->delete();

                foreach($attr as $k => $v) {
                    $info[] = array(
                        'pro_id'        => $post['pro_id'],
                        'attr_id'       => $v,
                    );
                }
//            dump($info);exit;
                if($this->pro_attr_model->addAll($info) == false) {
                    $iscommit = false;
                }
                $this->cart_model->where(['pro_id' => $data['pro_id']])->delete();
            }

            if($iscommit) {
                $this->product_model->commit();
                $this->success('', U('index'));
            } else {
                $this->product_model->rollback();
                $this->error();
            }
        } else {
            $id = intval(I("get.pro_id"));
            if (empty($id)) $this->error('empty');

            $result = $this->product_model->find($id);

            $this->assign('smeta', json_decode($result['smeta'], true));

            $this->assign('data', $result);

            $this->assign('attribute', $this->attribute_model->getAttrCheck(explode(',',$result['attr'])));
            $this->assign('category', $this->category_model->getCateOption($result['cate_id']));

            $this->display();
        }
    }


    /**
     * 删除
     */
    public function del()
    {
        $id = intval(I("get.pro_id"));
        if (empty($id)) $this->error('empty');
        if ($this->product_model->where(['pro_id' => $id])->save(['if_show' => ProductModel::SHOW_NO]) !== false) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 设置标签
     */
    public function setTag() {
        $pro_id     = I('post.pro_id');
        $tag_name   = I('post.tag_name');
        $tag_value  = I('post.tag_value');

        $data[$tag_name]    = $tag_value;
        if(in_array($tag_name, ['senior', 'high', 'primary', 'preschool'] )) {
            $data['hot_time']    = getTime();
        }
        if($this->product_model->where(['pro_id' => $pro_id])->save($data)) {
            $this->success();
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 获取第二级类型
     */
    /*public function getSecond() {
        $id = I('post.id');
        $category = $this->category_model->where(['parent_id' => $id, 'if_show' => CategoryModel::SHOW_ON])->select();
        $option_second = '';
        if($category) {
            foreach($category as $k => $v) {
                $option_second .= ' <option value="'.$v['cate_id'].'" >'.$v['cate_name'].'</option>';
            }
        } else {
            $option_second .= ' <option value="" >--暂无--</option>';
        }

        echo json_encode($option_second);
    }*/

    /**
     * 编辑属性
     */
    public function editAttr() {
        if(IS_POST) {
//            dump($_POST);die;
            $post = I('post.post');
            foreach ($post['detail_name'] as $k => $v) {
                $result[] = explode('|', $v);
            }
//            dump($result);//die;
            $detail = [];
            foreach ($result as $k => $v) {
//                dump($v);
                foreach ($v as $key => $val) {
                    $detail[] = [
                        'pro_id'        => I('post.pro_id'),
                        'attr_id'       => $post['attr_id'][$k],
                        'detail_name'   => $val,
                    ];
                }

            }

//            dump($detail);//die;
            $this->attr_detail_model->startTrans();
            $is_commit = true;

            //删除原来的
            if($this->attr_detail_model->where(['pro_id' => I('post.pro_id')])->find() ) {
                if($this->attr_detail_model->where(['pro_id' => I('post.pro_id')])->delete() == false) {
                    $is_commit = false;$error = 1;
                }
            }

            //添加详细属性
            if($this->attr_detail_model->addAll($detail) == false) {
                $is_commit = false; $error = 2;
            }

            //生成全排列规格
            $data = $this->attr_detail_model->where(['pro_id' => I('post.pro_id')])->field('de_id, attr_id, detail_name')->select();
//            dump($data);die;
            foreach ($data as $k => $v) {
                $rst[$v['attr_id']][] = $v;
            }

            //处理数组
            $detail_name = combine(dealArr($rst, 'detail_name'));
            $de_id = combine(dealArr($rst, 'de_id'));

//            dump($detail_name);
            //生成规格全排列数组
            $rst = [];
            foreach ($detail_name as $k => $v) {
                foreach ($v as $key => $val) {
                    $rst[$k] = [
                        'option_name'   => ($rst[$k]['option_name'] ? $rst[$k]['option_name'].$val : $val),
                        'combine_id'    => ($rst[$k]['combine_id'] ? $rst[$k]['combine_id'].','.$de_id[$k][$key] : $de_id[$k][$key]),
                        'pro_id'        => I('post.pro_id'),
                    ];

//                    dump($rst[$k]['option_name']);
//                    dump($rst[$k]);
                }
            }
//            dump($rst);
//            die;
            //删除原来的

            if($this->pro_option_model->where(['pro_id' => I('post.pro_id')])->find()) {
                 if($this->pro_option_model->where(['pro_id' => I('post.pro_id')])->delete() == false) {
                     $is_commit = false;$error = 3;
                 }
            }


            //添加新的
            if($this->pro_option_model->addAll($rst) == false) {
                $is_commit = false;$error = 4;
            }


//            $is_commit = false;
            if($is_commit) {
                $this->attr_detail_model->commit();
                $this->success('', U('index'));
            } else {
                $this->attr_detail_model->rollback();
                $this->error($error);
            }
        } else {
            $pro_id     = I('get.pro_id');
            $pro_attr   = $this->pro_attr_model
                ->alias('a')
                ->join('left join he_attribute as b on a.attr_id = b.attr_id')
                ->where(['a.pro_id' => $pro_id])
                ->field('a.pro_id, b.attr_id, b.attr_name')
                ->select();
            foreach ($pro_attr as $k => $v) {
                $detail = $this->attr_detail_model->where(['pro_id' => $pro_id, 'attr_id' => $v['attr_id']])->select();
                $name = array_column($detail,'detail_name');
                $pro_attr[$k]['detail'] = implode('|', $name);
            }
//            dump($pro_attr);
            $this->assign('attr', $pro_attr);
            $this->assign('pro_id', $pro_id);
            $this->display();
        }
    }

    public function editPrice() {
        if(IS_POST) {
//            dump($_POST);
            $post = I('post.post');
            $option_id  = $post['option_id'];
            $price      = $post['price'];
            $stock      = $post['stock'];
            foreach ($option_id as $k => $v) {

                $this->pro_option_model->where(['option_id' => $v])->save(['price' => $price[$k], 'stock' => $stock[$k]]);
            }
            $this->success('');

        } else {
            $pro_id = I('get.pro_id');

            $pro_option = $this->pro_option_model->where(['pro_id' => $pro_id])->select();
//            dump($pro_option);
            if(!$pro_option) {
                $this->error('请先完善属性信息');
            }
            $this->assign('lists', $pro_option);
            $this->display();
        }
    }


}